package utilx

import (
	"fmt"
	"net"
)

type MacIp struct {
	Address map[string]string
}

func NewMacIp() *MacIp {
	m := &MacIp{Address: make(map[string]string)}
	return m.getMacIp()
}

func (a *MacIp) IsMacExist(mac string) bool {
	for k, _ := range a.Address {
		if k == mac {
			return true
		}
	}
	return false
}
func (a *MacIp) IsIpExist(ip string) bool {
	for _, v := range a.Address {
		if v == ip {
			return true
		}
	}
	return false
}
func (a *MacIp) IsExist(mac, ip string) bool {
	for k, v := range a.Address {
		if k == mac && v == ip {
			return true
		}
	}
	return false
}

// mac作为key，ip作为value存储
func (a *MacIp) getMacIp() *MacIp {
	netInterfaces, err := net.Interfaces()
	if err != nil {
		fmt.Printf("fail to get net interfaces: %v", err)
		return a
	}

	for _, netInterface := range netInterfaces {
		mac := netInterface.HardwareAddr.String()
		if len(mac) == 0 {
			continue
		}

		adds, err := netInterface.Addrs()
		if err != nil {
			continue
		}
		for _, address := range adds {
			ipNet, isValidIpNet := address.(*net.IPNet)
			if isValidIpNet && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
				ip := ipNet.IP.String()
				a.Address[mac] = ip
			}
		}

	}
	return a
}
